#include "uBroadcast_B1.h"
#include "uBroadcast_UDP.h"

#include <stdio.h>
#include <sys/select.h>

char exitFlag = 0;
char debug = 0;

#define NDEBUG

int main(void) {
	// TODO allow to specify UDP port(s), serial port
	// --- Message ---
	uMessage msg;

	// --- BugOne connection ---
#ifndef NDEBUG
	printf("Connecting to BugOne sniffer ...\n");
#endif
	ub_B1 * b1_conn = ub_b1_connect("/dev/ttyUSB0");
	if (!b1_conn) {
		return 1;
	}

	// --- UDP connection ---
#ifndef NDEBUG
	printf("Connecting to UDP ...\n");
#endif
	ub_UDP * udp_conn = ub_udp_connect("router", UB_BROADCAST_UDP_PORT);
	if (!udp_conn) {
		ub_b1_disconnect(b1_conn);
		return 2;
	}

	// TODO attach to kill signal

	// --- Prepare select ---
	fd_set read_fds;
	FD_ZERO(&read_fds);

#ifndef NDEBUG
	printf("Waiting for message ...\n");
#endif
	while (!exitFlag) {
		// --- Init select ---
		FD_SET(b1_conn->serialPort, &read_fds);
		FD_SET(udp_conn->udpSocket, &read_fds);

		// --- Wait ---
		int res = select(FD_SETSIZE, &read_fds, NULL, NULL, NULL);
		if (res < 0) {
			perror("BugOne router select");
			continue;
		}

		// --- Message on BugOne ---
		if (FD_ISSET(b1_conn->serialPort, &read_fds)) {
			if (!ub_b1_recv(b1_conn, &msg)) {
				ub_udp_send(udp_conn, &msg);
#ifndef NDEBUG
				ub_debug(&msg);
#endif
			} else {
#ifndef NDEBUG
				fprintf(stderr, "Wrong BugOne message");
#endif
			}
		}
		// --- Message on UDP ---
		if (FD_ISSET(udp_conn->udpSocket, &read_fds)) {
			if (!ub_udp_recv(udp_conn, &msg)) {
				ub_b1_send(b1_conn, &msg);
#ifndef NDEBUG
				ub_debug(&msg);
#endif
			} else {
#ifndef NDEBUG
				fprintf(stderr, "Wrong UDP message");
#endif
			}
		}
	}

	// Signal received, exit
#ifndef NDEBUG
	printf("Disconnecting ...\n");
#endif
	ub_b1_disconnect(b1_conn);
	ub_udp_disconnect(udp_conn);

	return 0;
}
